//
//  NKRunViewController.m
//  NKMapTest
//
//  Created by SongGang on 2017/3/15.
//  Copyright © 2017年 NK. All rights reserved.
//

#import "NKMapViewController.h"
#import "MAMutablePolyline.h"
#import "MAMutablePolylineRenderer.h"
#import "NKRunInfoView.h"
#import "AMapRouteRecord.h"
#import "FileHelper.h"
#import "SystemInfo.h"
#import "RecordViewController.h"
#import "NKNavigationViewController.h"
#import "CustomAnnotationView.h"
#import "NKPointAnnotation.h"
#import "NKTileOverlay.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "NKCreatAnnotationViewController.h"
#import "NKLookAnnotationViewController.h"
#import "NKFIlePath.h"

@interface NKMapViewController () <MAMapViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) MAMapView *mapView;
// 用户位置图标
@property (nonatomic, strong) MAAnnotationView *userLocationAnnotationView;
// 用户详细即时数据
@property (nonatomic, strong) NKRunInfoView *infoView;
// 保持用户在屏幕显示
@property (nonatomic, strong) UIButton *locationBtn;

@property (nonatomic, strong) UIImage *imageLocated;
// 图源
@property (nonatomic, copy)  NSString *openstreetmap;

@property (nonatomic, strong) UIImage *imageNotLocate;
// 是否定位
@property (nonatomic, assign) BOOL isRecording;
// 是否定位成功（取决于定位精度）
@property (nonatomic, assign) BOOL isRecordSuccess;

@property (nonatomic, strong) MAMutablePolyline *mutablePolyline;

@property (nonatomic, strong) MAMutablePolylineRenderer *mutableView;
// 用于保存添加的坐标和标注坐标
@property (nonatomic, strong) AMapRouteRecord *currentRecord;
// 当前的位置
@property (nonatomic, strong) CLLocation *currentLocation;
// 标注点数组
@property (nonatomic, strong) NSMutableArray *pointAnnotationArray;
//  图源
@property (nonatomic, strong) NKTileOverlay  *customOverlay;
//
@property (nonatomic, strong) UIImagePickerController *imagePicker;
@end
 
@implementation NKMapViewController

// 谷歌混合卫星
//NSString * const openstreetmap = @"http://mt0.google.cn/vt/lyrs=y&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}";
// 谷歌卫星
//NSString * const openstreetmap = @"http://mt0.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}";
// 谷歌街道
//NSString * const openstreetmap = @"http://mt0.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}";
// 谷歌地形
//NSString * const openstreetmap = @"http://mt0.google.cn/vt/lyrs=p&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}";
// OCM街道
//NSString * const openstreetmap = @"http://tile.openstreetmap.org/{z}/{x}/{y}.png";
// OCM+Landscape地形图
//NSString * const openstreetmap = @"https://c.tile.thunderforest.com/landscape/{z}/{x}/{y}.png?apikey=813808e22af5488cabc07d692f2fd21c";


- (NKTileOverlay *)customOverlay {

    if (!_customOverlay) {
        _customOverlay = [[NKTileOverlay alloc] initWithURLTemplate:@""];
        _customOverlay.minimumZ = 1;
        _customOverlay.maximumZ = 23;
        _customOverlay.boundingMapRect = MAMapRectWorld;
        [self.mapView insertOverlay:_customOverlay aboveOverlay:self.mutablePolyline];
    }
    return _customOverlay;
}

- (NSMutableArray *)pointAnnotationArray {

    if (!_pointAnnotationArray) {
        _pointAnnotationArray = [NSMutableArray array];
    }
    return _pointAnnotationArray;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self initView];

    [self initData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAnnotationPoint:) name:NotificationNameWithAddAnnotationPonit object:nil];
}

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    self.navigationController.navigationBarHidden = YES;
    [self.mapView addOverlay:self.mutablePolyline];
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
}


- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    [[EMCDDeviceManager sharedInstance] stopPlaying];
}

- (void)initView {
    
    self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.zoomLevel = 20.0;
    self.mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    self.mapView.showsCompass = YES;
    self.mapView.showsScale = YES;
    self.mapView.rotateCameraEnabled = NO;
    self.mapView.scaleOrigin = CGPointMake(120, NKScreenHeight - 25);
    self.mapView.compassOrigin = CGPointMake(NKScreenWidth - 40, NKScreenHeight - 40);
    self.mapView.showsIndoorMap = NO;
    self.mapView.delegate = self;
    self.mapView.customizeUserLocationAccuracyCircleRepresentation = YES;
    [self.view addSubview:self.mapView];

    self.infoView = [[NKRunInfoView alloc] initWithFrame:CGRectMake(10, 35, 170, 170)];
    [self.view addSubview:self.infoView];
    
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    startButton.frame = CGRectMake(self.view.NK_centerX - 25, NKScreenHeight - 100, 40, 40);
    [startButton setImage:[UIImage imageNamed:@"run_start"] forState:UIControlStateNormal];
    [startButton addTarget:self action:@selector(actionRecordAndStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startButton];
    
    // 追踪
    UIButton *trackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    trackButton.frame = CGRectMake(20, NKScreenHeight - 160, 40, 40);
    [trackButton setImage:[UIImage imageNamed:@"trackButton"] forState:UIControlStateNormal];
    [trackButton addTarget:self action:@selector(actionLocation) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:trackButton];

    
    // 图源
    UIButton *mapScoureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    mapScoureButton.frame = CGRectMake(20, NKScreenHeight - 100, 40, 40);
    [mapScoureButton setImage:[UIImage imageNamed:@"mapScoure"] forState:UIControlStateNormal];
    [mapScoureButton addTarget:self action:@selector(showmapScoure) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:mapScoureButton];
    
    // 拍照
    UIButton *cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cameraButton.frame = CGRectMake(NKScreenWidth -40 - 20, NKScreenHeight - 100, 40, 40);
    [cameraButton setImage:[UIImage imageNamed:@"camera"] forState:UIControlStateNormal];
    [cameraButton addTarget:self action:@selector(goToCamera:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cameraButton];


    UIButton *RunListButton = [UIButton buttonWithType:UIButtonTypeCustom];
    RunListButton.frame = CGRectMake(NKScreenWidth - 50, 35, 40, 40);
    [RunListButton setImage:[UIImage imageNamed:@"RunList"] forState:UIControlStateNormal];
    [RunListButton addTarget:self action:@selector(lookRunlist) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:RunListButton];
    
}

- (void)initData {
    
    self.mutablePolyline = [[MAMutablePolyline alloc] initWithPoints:@[]];
    self.isRecording = NO;
    
}

- (void)cleanData {

    self.isRecording = NO;
    [self.mapView removeAnnotations:self.pointAnnotationArray];
    [self.mutablePolyline removeAllPoints];
    [self.mutableView referenceDidChange];
    self.infoView.textView.text = @"";
    [self.pointAnnotationArray removeAllObjects];
    self.currentRecord = nil;
}
// 开始或者停止记录轨迹
- (void)actionRecordAndStop:(UIButton *)btn {

    if ((self.currentRecord == nil || self.currentRecord.numOfLocations < 2) && self.isRecording )
    {
        [SVProgressHUD showErrorWithStatus:@"最少记录两个点"];
        return;
    }
    
    self.isRecording = !self.isRecording;
    
    if (self.isRecording) {
        
        
        [self.infoView.control setTitle:@"徒步开始" forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"run_stop"] forState:UIControlStateNormal];
        if (self.currentRecord == nil)
        {
            self.currentRecord = [[AMapRouteRecord alloc] init];
        }
        [self setBackgroundModeEnable:YES];
    }
    else
    {
        [btn setImage:[UIImage imageNamed:@"run_start"] forState:UIControlStateNormal];
        [self setBackgroundModeEnable:NO];
        [self actionSaveAndDeleteData];
    }
}




// 保存并删除之前数据
- (void)actionSaveAndDeleteData {
    
    __weak typeof(self) weakSelf = self;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"路线命名" message:@"注意：以拼音命名" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.clearsOnBeginEditing = YES;
        textField.text = weakSelf.currentRecord.title;
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UITextField *textField = alert.textFields.firstObject;
         BOOL result = [weakSelf.currentRecord saveRecordWithFileName:textField.text];
        if (result)
        {
            [self.infoView.control setTitle:@"保存成功" forState:UIControlStateNormal];
            [self cleanData];
        }
        else
        {
            [self.infoView.control setTitle:@"保存失败" forState:UIControlStateNormal];
        }

    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];

}


// 跳转轨迹列表
- (void)lookRunlist {
    
    NKNavigationViewController *nav = [[NKNavigationViewController alloc] initWithRootViewController: [[RecordViewController alloc] init]];
    [self presentViewController:nav animated:YES completion:nil];
}

// 开始添加标记
- (void)goToCamera:(UIButton *)sender {

    if (self.isRecording) {
        
        if (self.isRecordSuccess) {
            
            NKCreatAnnotationViewController *annotationVC = [[NKCreatAnnotationViewController alloc] init];
            [self presentViewController:annotationVC animated:YES completion:^{
                
                annotationVC.pathName = self.currentRecord.title;
                annotationVC.currentLocation  = self.currentLocation;
            }];
            
        }else {
        
            [SVProgressHUD showErrorWithStatus:@"定位不成功，请站在空旷地方定位"];
        }
    }else {
    
         [SVProgressHUD showErrorWithStatus:@"请先开始徒步，并定位成功"];
        
    }
    
}

// 添加标记
- (void)addAnnotationPoint:(NSNotification *)notification {
    
    NSDictionary *dict = notification.userInfo;
    [self.currentRecord addAnnotationLocation: self.currentLocation withImagePath:dict[@"imagePath"] withAudioPath:dict[@"audioPath"]];
    CLLocation *location = dict[@"currentLocation"];
    NKPointAnnotation *pointAnnotation = [[NKPointAnnotation alloc] init];
    pointAnnotation.coordinate = location.coordinate;
    pointAnnotation.title = [NSString stringWithFormat: @"%ld",self.currentRecord.numOfAnnotationLocation];
    [self.pointAnnotationArray addObject:pointAnnotation];
    [self.mapView addAnnotation:pointAnnotation];
    
}

// 查看标记
- (void) showAnnotationView: (UITapGestureRecognizer *)tapGestureRecognizer {

    CustomAnnotationView *annotationView = (CustomAnnotationView *)tapGestureRecognizer.view;
    NSInteger index = [annotationView.annotation.title integerValue] - 1;
    NSDictionary *dict = self.currentRecord.filePaths[index] ;
    NKLookAnnotationViewController *lookVC = [[NKLookAnnotationViewController alloc] init];
    if ([dict[@"imagePath"] isEqualToString:@"nil"]) {
        
         lookVC.imagePath = dict[@"imagePath"];
        
    }else {
    
        lookVC.imagePath = [[FileHelper baseDir] stringByAppendingPathComponent:dict[@"imagePath"]];
    }
    
    if ([dict[@"audioPath"] isEqualToString:@"nil"]) {
        
        lookVC.audioPath = dict[@"audioPath"];
        
    }else {
        
        lookVC.audioPath = [[FileHelper baseDir] stringByAppendingPathComponent:dict[@"audioPath"]];
    }

    [self presentViewController:lookVC animated:YES completion:nil];
    
}

// 切换图源
- (void)showmapScoure {

    __weak typeof (self) weakSelf = self;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"切换图源" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"高德" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf.mapView removeOverlay:weakSelf.customOverlay];
        weakSelf.customOverlay = nil;
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"谷歌混合卫星" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

     weakSelf.customOverlay =  [weakSelf.customOverlay initWithURLTemplate: @"http://mt0.google.cn/vt/lyrs=y&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}"];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"谷歌卫星" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

         weakSelf.customOverlay =  [weakSelf.customOverlay initWithURLTemplate: @"http://mt0.google.cn/vt/lyrs=s&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}"];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"谷歌街道" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     
        weakSelf.customOverlay =  [weakSelf.customOverlay initWithURLTemplate: @"http://mt0.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}"];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"谷歌地形" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        weakSelf.customOverlay =  [weakSelf.customOverlay initWithURLTemplate: @"http://mt0.google.cn/vt/lyrs=p&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}&scale={scale}"];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OCM街道" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
   
        weakSelf.customOverlay =  [weakSelf.customOverlay initWithURLTemplate: @"http://tile.openstreetmap.org/{z}/{x}/{y}.png"];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OCM等高线" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
 
        weakSelf.customOverlay =  [weakSelf.customOverlay initWithURLTemplate: @"https://c.tile.thunderforest.com/landscape/{z}/{x}/{y}.png?apikey=813808e22af5488cabc07d692f2fd21c"];
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

// 切换定位模式
- (void)actionLocation
{
    if (self.mapView.userTrackingMode == MAUserTrackingModeFollow) {
        
        [self.mapView setUserTrackingMode:MAUserTrackingModeNone animated:YES];
        
    }else {
    
         [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES];
    }
}

// 地图缩放完成
- (void)mapView:(MAMapView *)mapView mapWillZoomByUser:(BOOL)wasUserAction {

    if (wasUserAction) {
        
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%.f",mapView.zoomLevel]];
        
    }
}

// 切换后台定位
- (void)setBackgroundModeEnable:(BOOL)enable
{
    self.mapView.pausesLocationUpdatesAutomatically = !enable;
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0)
    {
        self.mapView.allowsBackgroundLocationUpdates = enable;
    }
}

#pragma mark - mapview delegate
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    
    MAAnnotationView *view = views[0];
    
    // 放到该方法中用以保证userlocation的annotationView已经添加到地图上了。
    if ([view.annotation isKindOfClass:[MAUserLocation class]])
    {
        MAUserLocationRepresentation *pre = [[MAUserLocationRepresentation alloc] init];
        pre.image = [UIImage imageNamed:@"userPosition"];
        pre.lineWidth = 0.1;
        [self.mapView updateUserLocationRepresentation:pre];
        view.calloutOffset = CGPointMake(0, 0);
        self.userLocationAnnotationView = view;
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {

    if ([annotation isKindOfClass:[NKPointAnnotation class]]) {
        
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        annotationView.image = [UIImage imageNamed:@"audioPoint"];
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);
        annotationView.canShowCallout = NO;
        annotationView.selected = YES;
        annotationView.calloutView.title = annotation.title;
        [annotationView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showAnnotationView:)]];
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    
    if (!updatingLocation && self.userLocationAnnotationView != nil)
    {
        self.currentLocation = userLocation.location;
        [UIView animateWithDuration:0.1 animations:^{
            
            double degree = userLocation.heading.trueHeading;
            self.userLocationAnnotationView.transform = CGAffineTransformMakeRotation(degree * M_PI / 180.f );
            self.infoView.angle = degree;
        }];
    }
    
    if (!updatingLocation || !self.isRecording)
    {
        return;
    }
 
    self.isRecordSuccess = NO;
    
    // 精确度大于0小于100
    if (userLocation.location.horizontalAccuracy < 100 && userLocation.location.horizontalAccuracy > 0) {
        self.isRecordSuccess = YES;
        // 移动的距离
        double lastDis = [userLocation.location distanceFromLocation:self.currentRecord.endLocation];

        // 距离大于1或者后退
        if (lastDis < 0.0 || lastDis > 1)
        {
            
            // 用于保存CLLocation
            [self.currentRecord addLocation:userLocation.location];
            // 线路添加坐标，开始描线
            [self.mutablePolyline appendPoint: MAMapPointForCoordinate(userLocation.location.coordinate)];
            // 批量将MAMapPoint转换为opengles可以直接使用的坐标
            [self.mutableView referenceDidChange];
            // 当前地图的中心点，改变该值时，地图的比例尺级别不会发生变化
            [self.mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];
    
        }
    }
    
    // 显示即时数据
        [self.infoView showStatusWith:self.currentRecord];
}

- (void)mapView:(MAMapView *)mapView  didChangeUserTrackingMode:(MAUserTrackingMode)mode animated:(BOOL)animated
{
    if (mode == MAUserTrackingModeNone)
    {
        [self.locationBtn setImage:self.imageNotLocate forState:UIControlStateNormal];
    }
    else
    {
        [self.locationBtn setImage:self.imageLocated forState:UIControlStateNormal];
    }
}

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{

    if ([overlay isKindOfClass:[MAMutablePolyline class]])
    {
        MAMutablePolylineRenderer *view = [[MAMutablePolylineRenderer alloc] initWithMutablePolyline:overlay];
        view.lineWidth = 5.0;
        view.strokeColor = [UIColor redColor];
        _mutableView = view;
        return view;
    }
    
    if ([overlay isKindOfClass:[NKTileOverlay class]]) {

        MATileOverlayRenderer *renderer = [[MATileOverlayRenderer alloc] initWithTileOverlay:overlay];
       
        return renderer;
    }
    
    if ([overlay isKindOfClass:[MACircle class]]) {
        
        MACircleRenderer *circleView = [[MACircleRenderer alloc] initWithOverlay:overlay];
        circleView.fillColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        circleView.strokeColor =  [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
        return circleView;
    }
    
    return nil;
}



@end
